package com.xiaoma.bingox.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dexcoder.commons.pager.Pager;
import com.xiaoma.bingox.entity.Company;
import com.xiaoma.bingox.service.CompanyService;

@Controller
@RequestMapping("/app/company")
public class CompanyController {

    @Autowired
    private CompanyService companyService;
    
    @RequestMapping(method = RequestMethod.GET)
    public String index(){
        return "/company/index";
    }
    
    @RequestMapping(value="/datas",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> loadDatas(Integer page, Integer rows){
        page = page == null ? 1 : page;
        rows = rows == null ? 50 : rows;
        Map<String,Object> result = new HashMap<String, Object>();
        Pager pager = companyService.findAll(page, rows);
        result.put("rows", pager.getList());
        result.put("total", pager.getItemsTotal());
        return result;
    }
    
    @RequestMapping(value="/save", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> save(Company company){
        Map<String,Object> result = new HashMap<String, Object>();
        company.setCreatedAt(new Date());
        try {
            companyService.save(company);
            result.put("status", 1);
        } catch(Exception e) {
            result.put("status", 0);
        }
        return result;
    }
    
    @RequestMapping(value="/update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> update(Company company){
        Map<String,Object> result = new HashMap<String, Object>();
        try {
            companyService.update(company);
            result.put("status", 1);
        } catch(Exception e) {
            result.put("status", 0);
        }
        return result;
    }
    
    
    @RequestMapping(value="/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> delete(@PathVariable Integer id){
        Map<String,Object> result = new HashMap<String, Object>();
        try {
            companyService.delete(id);
            result.put("status", 1);
        } catch(Exception e) {
            result.put("status", 0);
            result.put("message", e.getMessage());
        }
        return result;
    }
}